<?php

namespace app\scm\controller;

use app\admin\common\Base;
use think\Db;
use app\scm\model\Invpu as Model;
use app\admin\common\Excel;
class Invpureport extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $sql = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->field('a.good_id, a.order_id, a.shuliang, a.unit_id, a.store_id, a.price, a.addtime, a.tax_e, a.total_price, b.*')->where('a.type', 'in', '4,5')->where('b.o_type', 'in', '4,5')->where(['a.is_del' => 0, 'a.enterprise_id' => $this->EnterpriseId]);
            if (isset($data['startdate']) && isset($data['enddate'])) {
                $sql = $sql->where('b.addtime', '>=', strtotime($data['startdate']))->where('b.addtime', '<=', strtotime($data['enddate']));
            }
            $sql = $sql->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
            //search
            $data['supplierid'] = $data['supplierid'] ?? '';
            $sql = $data['supplierid'] == '' ? $sql : $sql->where('b.user_id', $data['supplierid']);
            $sql = $data['goods_id'] == '' ? $sql : $sql->where('a.good_id', $data['goods_id']);
            $sql = $data['store_id'] == '' ? $sql : $sql->where('a.store_id', $data['store_id']);

            // 高级搜索
            extract($data);
            $sql = empty($sn) ? $sql : $sql->where('b.sn', 'like', '%' . $sn . '%');
            $sql = empty($store_id) ? $sql : $sql->where('a.store_id', $store_id);
            $sql = empty($mark) ? $sql : $sql->where('mark', $mark);

            // 供应商类别
            if (!isset($data['supplier_category_id']) || $data['supplier_category_id'] == 0 || $data['supplier_category_id'] == '') {
            } else {
                $c = Db::name('customer')->where('category_id', $data['supplier_category_id'])->select();
                $c['ids'] = implode(',', array_column($c, 'id'));
                $sql->where('b.user_id', 'in', $c['ids']); //商品类别
            }

            // 商品类别
            if (!isset($data['goods_category_id']) || $data['goods_category_id'] == 0 || $data['goods_category_id'] == '') {
            } else {
                $g = Db::name('goods')->where('goods_category_id', $data['goods_category_id'])->select();
                $g['ids'] = implode(',', array_column($g, 'id'));
                $sql->where('a.good_id', 'in', $g['ids']); //商品类别
            }

            $list0 = $sql->select();
            $count = count($list0);
            $list = array_slice($list0, $start, $limit);

            foreach ($list as $key => $value) {
                $goods = Db::name('goods')->where('id', $value['good_id'])->find();
                $list[$key]['goods_sn'] = $goods['sn'];
                $list[$key]['goods_name'] = $goods['name'];
                $list[$key]['goods_model'] = $goods['model'];
                $list[$key]['goods_code'] = $goods['code'];
                $list[$key]['unit_name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
                $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
                $list[$key]['customer_name'] = Db::name('customer')->where('id', $value['user_id'])->value('name');
                $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
                $list[$key]['o_type_name'] = $value['o_type'] == 4 ? '购货' : '退货';

                // 处理退货数据
                if ($value['o_type'] == 5) {
                    $list[$key]['shuliang'] = 0 - $value['shuliang'];
                    $list[$key]['payment'] = 0 - $value['payment'];
                    $list[$key]['purchase_cost'] = 0 - $value['purchase_cost'];
                    $list[$key]['tax_e'] = 0 - $value['tax_e'];
                    $list[$key]['total_price'] = 0 - $value['total_price'];
                }
            }

            return $this->grid_data($list, $count, $page, $limit);
        }

        $customer = Db::name('customer')->where('is_customer', 'in', '1,3')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        $goods = Db::name('goods')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();

        if ($data['doubleclick'] ?? false) {
            $this->assign('doubleclick', $data['doubleclick']);
            $this->assign('goods_id', $data['goods_id']);
            $this->assign('store_id', $data['store_id']);
        } else {
            $this->assign('doubleclick', 0);
        }

        $this->assign('customer', $customer);
        $this->assign('goods', $goods);
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    //编辑栏目1-1
    public function edit($id)
    {
        $info = Db::name('invpu')->where('id', $id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }
    //编辑栏目1-2
    public function save()
    {
        // 启动事务
        Db::startTrans();
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $model = new Model();
        if (empty($data['id'])) {
            $data['addtime'] = time();
            $data['enterprise_id'] = $this->EnterpriseId;
            $result = $model->allowField(true)->save($data);
            $id = $model->id;
            if ($result) {
                $status = 1;
                $msg = "添加成功";
            }
        } else {
            $id = $data['id'];
            $result = $model->allowField(true)->save($data, ["id" => $id]);
            if ($result) {
                $status = 1;
                $msg = "更新成功";
            }
        }
        //子表
        self::saveDefautl($data, $id);
        Db::commit();

        return json(['status' => $status, 'msg' => $msg]);
    }

    private function saveDefautl($data, $pid)
    {
        if (isset($data['goods_id'])) {
            $invpuGoods = [];
            foreach ($data['goods_id'] as $keys => $v) {
                $temp = [
                    'invpu_id' => $pid,
                    'goods_id' => $v,
                    'goods_mark' => $data['goods_mark'][$keys],
                    'unit_id' => $data['unit'][$keys],
                    'store_id' => $data['store_id'][$keys],
                    'number' => $data['number'][$keys],
                    'base_unit_id' => $data['base_unit_id'][$keys],
                    'base_number' => $data['base_number'][$keys],
                    'buy_price' => $data['buy_price'][$keys],
                    'total_tax_price' => $data['total_tax_price'][$keys],
                    'discount_rate' => $data['discount_rate'][$keys],
                    'discount_price' => $data['discount_price'][$keys],
                    'price' => $data['price'][$keys],
                    'tax_rate' => $data['tax_rate'][$keys],
                    'tax_price' => $data['tax_price'][$keys],
                    'sum_price_tax' => $data['sum_price_tax'][$keys],
                    'purchase_price' => $data['purchase_price'][$keys],
                    'mark' => $data['mark'][$keys],
                    'purchase_sn' => $data['purchase_sn'][$keys],
                    'enterprise_id' => $this->EnterpriseId
                ];
                array_push($invpuGoods, $temp);
            }

            $rest = Db::name('invpu_goods')->insertAll($invpuGoods);
            if (!$rest) {
                // 回滚事务
                Db::rollback();
                return json(['status' => 0, 'msg' => '添加失败']);
            }
        } else {
            // 回滚事务
            Db::rollback();
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }

    //删除栏目1-1
    public function del($id)
    {
        $status = 0;
        $msg = "操作失败";
        $del = Db::name('invpu')->where('id', $id)->update(["is_del" => 1]);
        if ($del) {
            $status = 1;
            $msg = "删除成功";
        }
        return json(['status' => $status, 'msg' => $msg]);
    }
    public function export(){
        $data = $this->request->param();
        $time = '日期：'.$data['startdate'].'至'.$data['enddate'];
        $arr_data = explode(" ",$data['rowid']);

        $title = [
            'addtime' => '采购日期',
            'sn' => '采购单据号',
            'type'=>'业务类别',
            'customer_name'=>'供应商',
            'goods_sn' => '商品编号',
            'goods_name'=>'商品名称',
            'goods_code' => '商品条码',
            'goods_model'=>'规格型号',
            'unit_name' => '单位',
            'store_name' => '仓库',
            'shuliang' => '数量',
            'price'=>'单价',
            'hs_price' => '含税单价',
            'jine' => '采购金额',
            'purchase_cost' => '采购费用',
            'tax_e' => '税额',
            'total_price' => '价税合计',
            'mark' => '分录备注',
        ];
        $arr_list = [];
        $list = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->where('a.type', 'in', '4,5')->where('b.o_type', 'in', '4,5')->where('order_id','in',$arr_data)->where(['a.is_del' => 0, 'a.enterprise_id' => $this->EnterpriseId])->select();
        foreach ($list as $key => $value) {
            $goods = db('goods')->where(['is_del'=>0,'enterprise_id'=>$this->EnterpriseId])->where('id',$value['good_id'])->find();
            $list[$key]['goods_sn'] = $goods['sn'];
            $list[$key]['goods_name'] = $goods['name'];
            $list[$key]['goods_model'] = $goods['model'];
            $list[$key]['goods_code'] = $goods['code'];
            $list[$key]['unit_name'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
            $list[$key]['addtime'] = date('Y-m-d', $value['addtime']);
            $list[$key]['customer_name'] = Db::name('customer')->where('id', $value['user_id'])->value('name');
            $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
            array_push($arr_list,$list[$key]);
        }
        $tit = [
            'addtime' =>$time,
            'sn' => '',
            'type'=>'',
            'customer_name'=>'',
            'goods_sn' => '',
            'goods_name'=>'',
            'goods_code' => '',
            'goods_model'=>'',
            'unit_name' => '',
            'store_name' => '',
            'shuliang' => '',
            'price'=>'',
            'hs_price' => '',
            'jine' => '',
            'purchase_cost' => '',
            'tax_e' => '',
            'total_price' => '',
            'mark' => '',
        ]; 
        
        // halt($arr_list);
        // array_multisort($distance, SORT_DESC, $arr_list);//按照ID大小排序
        //添加标题到数组头部
        array_unshift($arr_list,$title);
        array_unshift($arr_list,$tit);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <3 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
         //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }
        $merge=[];
        $options=[];
        $o_type=-1;
        $options=[
            'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R'],//居中
            'bold'=>['A1:R5','A4:R5'],//加粗
            'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
        ];
        $title=[//标题
            'title'=>"商品采购明细表",
            'max_zimu'=>"R",
            'number'=>'3',
        ];
        $excel_export_title="商品采购明细表_" . date('Y-m-d_His') . '.xlsx';//文件名称
        $excel = new Excel();
        $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
        
        exit();
    }
}
